import java.util.ArrayList;
import java.util.function.Predicate;
import java.io.*;

// 电话簿条目
class Record implements Serializable {
	public Record(String name, String number) {
		this.name = name;
		this.number = number;
	}
	String name;
	String number;
}

// 电话簿, 扮演model的角色
// 里面没有一点与用户的交互(既不向屏幕输出,也不读键盘)
class PhoneBook {
	ArrayList<Record> mList;
	BufferedReader mIn = new BufferedReader(new InputStreamReader(System.in));

	@SuppressWarnings("unchecked")
	void load() throws Exception {
		File phone_book_data_file = new File("phonebook.dat");
		if (phone_book_data_file.exists()) {
			ObjectInput fin = new ObjectInputStream(new FileInputStream("phonebook.dat"));
			mList = (ArrayList<Record>)fin.readObject();
			fin.close();
		}
		else {
			mList = new ArrayList<>();
		}

	}

	void store() throws Exception {
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("phonebook.dat"));
		out.writeObject(mList);
		out.close();
	}

	void delete(String name) {
		mList.removeIf(new Predicate<Record>() {

			@Override
			public boolean test(Record t) {
				if (name.equals(t.name))
					return true;
				return false;
			}
			
		});
	}

	void add(String name, String number){
		mList.add(new Record(name, number));
	}

	ArrayList<Record> getRecordList() {
		return mList;
	}

}

// 扮演controller以及view的角色
// 与用户的交互全放在此处
public class Main {

	BufferedReader mIn = new BufferedReader(new InputStreamReader(System.in));
	PhoneBook mBook;

	Main(PhoneBook book) {
		mBook = book;
	}

	void work() throws Exception {

		mBook.load();

		String prompt = """
			[q]uit
			[l]ist all records
			[a]dd a new record
			[d]elete an existed record
			""";

		boolean loop = true;
		while (loop) {
			System.out.println(prompt);
			System.out.print("please input an action: ");
			String choice = mIn.readLine();
			
			switch (choice) {
				case "q":
					loop = false;
					break;
				case "l": // list
					list();
					break;
				case "a": // add
					add();
					break;
				case "d": // delete
					delete();
					break;
				}
		
		}

		mBook.store();

	}

	void add() throws IOException {
		System.out.print("name: ");
		String name = mIn.readLine();
		System.out.print("number: ");
		String number = mIn.readLine();
		mBook.add(name, number);
	}

	void list() throws Exception {
		ArrayList<Record> list = mBook.getRecordList();
		for (Record r : list) {
			System.out.println(r.name);
			System.out.println(r.number);
			System.out.println("--------------------------------------");
		}
	}	

	void delete() throws Exception {
		System.out.println("name to delete: ");
		String name = mIn.readLine();
		mBook.delete(name);
	}

	public static void main(String[] args) throws Exception {

		// model
		PhoneBook book = new PhoneBook();

		// controller
		Main m = new Main(book);
		m.work();
	}

}

